﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Mock.Dotnet.Utils
{
    public class RandomDateUtil
    {
        private static readonly Random RANDOM = new Random();

        public static DateTime RandomDate(string min, string max)
        {
            if (min == null) min = "1970-01-01 00:00:00";
            if (max == null) max = "2099-12-31 23:59:59";
            long minDate = ConvertDateTimeToLong(DateTime.Parse(min));
            long maxDate = ConvertDateTimeToLong(DateTime.Parse(max));
            double Key = RANDOM.NextDouble();
            return ConvertLongToDateTime(minDate + (long)((maxDate - minDate) * Key));
        }

        public static long ConvertDateTimeToLong(DateTime dt)
        {
            DateTime dtStart = new DateTime(1970, 1, 1);
            if (dtStart == dt) return 0;
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks;
            timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4));
            return timeStamp;
        }

        private static DateTime ConvertLongToDateTime(long d)
        {
            DateTime dtStart = new DateTime(1970, 1, 1);
            if (d == 0) return dtStart;
            long lTime = long.Parse(d + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }
    }
}